class SaveSystem {
    static save(gameState) {
        const saveData = {
            timestamp: Date.now(),
            character: {
                id: gameState.character.id,
                name: gameState.character.name,
                hp: gameState.character.hp,
                maxHp: gameState.character.maxHp,
                gold: gameState.character.gold,
                inventory: gameState.character.inventory,
                level: gameState.character.level,
                exp: gameState.character.exp,
                images: gameState.character.images,
                stats: {
                    attack: gameState.character.attack,
                    defense: gameState.character.defense,
                    speed: gameState.character.speed
                },
                buffs: gameState.character.buffs ? 
                    Array.from(gameState.character.buffs).map(([key, value]) => ({
                        key,
                        value: {
                            duration: value?.duration,
                            effect: value?.effect
                        }
                    })) : [],
                skills: gameState.character.skills ? Array.from(gameState.character.skills) : []
            },
            world: gameState.world,
            level: gameState.level,
            currentNode: gameState.currentNode ? {
                type: gameState.currentNode.type,
                x: gameState.currentNode.x,
                y: gameState.currentNode.y,
                content: gameState.currentNode.content,
                children: Array.isArray(gameState.currentNode.children) ? 
                    gameState.currentNode.children.map(child => ({
                        type: child.type,
                        x: child.x,
                        y: child.y,
                        content: child.content
                    })) : []
            } : null,
            mapState: {
                scale: gameState.mapView?.scale || 1,
                offsetX: gameState.mapView?.offsetX || 0,
                offsetY: gameState.mapView?.offsetY || 0
            }
        };
        
        try {
            localStorage.setItem('gameState', JSON.stringify(saveData));
            return saveData;
        } catch (e) {
            console.error('Failed to save game:', e);
            return null;
        }
    }

    static load() {
        const saveData = localStorage.getItem('gameState');
        if (!saveData) return null;
        
        try {
            const data = JSON.parse(saveData);
            if (!data || !data.character || !data.character.id) {
                throw new Error('存档数据不完整');
            }
            
            // 重建角色对象
            const character = characterManager.createCharacter(data.character.id);
            
            // 确保 buffs 是一个有效的数组
            const buffs = new Map();
            if (Array.isArray(data.character.buffs)) {
                data.character.buffs.forEach(buff => {
                    if (buff && buff.key && buff.value) {
                        buffs.set(buff.key, buff.value);
                    }
                });
            }

            // 确保 skills 是一个有效的数组
            const skills = new Set(Array.isArray(data.character.skills) ? data.character.skills : []);

            // 合并角色数据
            Object.assign(character, {
                ...data.character,
                buffs,
                skills
            });
            
            // 重建节点对象
            const currentNode = data.currentNode ? this._reconstructNode(data.currentNode) : null;
            
            return {
                character,
                world: data.world,
                level: data.level,
                currentNode,
                timestamp: data.timestamp,
                mapState: data.mapState || { scale: 1, offsetX: 0, offsetY: 0 }
            };
        } catch (e) {
            console.error('Failed to load save:', e);
            return null;
        }
    }

    static _reconstructNode(nodeData) {
        if (!nodeData || typeof nodeData !== 'object') return null;
        
        return {
            type: nodeData.type || 'unknown',
            x: nodeData.x || 0,
            y: nodeData.y || 0,
            content: nodeData.content || {},
            children: Array.isArray(nodeData.children) ? 
                nodeData.children.map(child => this._reconstructNode(child)).filter(Boolean) : []
        };
    }

    static formatDate(timestamp) {
        const date = new Date(timestamp);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
} 